/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/11/14
 **/

let request = require('request');
var path  =require('path');
import  * as npmLoadUtil from '../util/npm-load-util';

let initService ={};
let xSiteJsCssRel;

export  async function initActiveXsite (version) {
    // Object.keys(result.versions)[0];
    if (!version) {
        let pageageName = '@qianmi/x-site';
        let result  = await httpget({fileUrl:'http://registry.npm.qianmi.com/'+pageageName});
        version = Object.keys(result['versions'])[0];
    }

    let name ="@qianmi/x-site";
    let distDir =path.join(__dirname,"../temp");
    let npmPackageDir  = await npmLoadUtil.loadNpmPackage({version,  name,  distDir});

    //删除require缓存
    delete require.cache[require.resolve('../temp/@qianmi/x-site/auto/bundle-map')];
    //取出当前生效的JS CSS引用信息..
    xSiteJsCssRel  = require('../temp/@qianmi/x-site/auto/bundle-map');
}


/**
 * 获取建站项目生效的JS与CSS地址
 * @return {any}
 */
export async function getXSiteJsCssRel (){

    if(xSiteJsCssRel){
        return xSiteJsCssRel;
    }else {
        await initActiveXsite('');
        return xSiteJsCssRel;
    }
};

async function httpget({fileUrl}){
    return new Promise((resolve,reject)=>{
        request.get({url:fileUrl, json:true}, function(err, res, body) {
            if (!err && res.statusCode === 200) {
                resolve(body);
            } else {
                reject(err);
            }
        })
    });
}

// initActiveXsite();
